<template>
  <div class="gl_contentBox gl_heightFull">
    <div class="gl_searchBox gl_mb_15">
      <el-row :gutter="20">
        <el-col :md="6" :lg="4">
          <p>{{ $t('messageCenter.state') }}</p>
          <el-select v-model="Api_GET_MessageGetReceivingMessagesQO.getMessageType" size="mini" filterable @change="refreshList()">
            <el-option v-for="item in statusList" :key="item.code" :label="item.value" :value="item.code" />
          </el-select>
        </el-col>
        <el-col :md="8" :lg="6">
          <el-button style="margin-top:27px" type="primary" size="mini" @click="query">{{ $t('button.query') }}</el-button>
        </el-col>
      </el-row>
    </div>
    <el-row :gutter="20" class="gl_mb_15">
      <el-col :md="8" :lg="6">
        <el-button :loading="deleteLoading" type="danger" size="mini" @click="removeMore">{{ $t('button.delete') }}</el-button>
        <el-button size="mini" plain @click="changeState">{{ $t('button.read') }}</el-button>
        <!-- <el-button type="primary" size="mini" @click="writeMessage">{{ $t('button.toWrite') }}</el-button> -->
      </el-col>
    </el-row>
    <el-table ref="inboxTable" v-loading="loading" :data="inboxTable" size="mini" @selection-change="selection">
      <el-table-column type="selection" label-class-name="selection" />
      <el-table-column :label="$t('table.title')">
        <template slot-scope="scope">
          <!-- <i v-if="isIconState" class="iconfont icon_state icon_color" style="vertical-align: middle;" /> -->
          <i v-if="!scope.row.isRead" class="iconfont icon_state icon_color" style="vertical-align: middle; font-size:24px" />
          <span>{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="sendUserName" :label="$t('table.sender')" />
      <el-table-column :label="$t('table.message')">
        <template slot-scope="scope">
          <span v-html="scope.row.content">
            <!-- {{ scope.row.message }} -->
          </span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.time')">
        <template slot-scope="{row}">
          <span v-if="row.createTime">
            {{ row.createTime | FormatDate('yyyy-MM-dd HH:mm:ss') }}
            <!-- {{ row.createTime }} -->
          </span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="$t('table.actions')" width="300">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="detail(scope.row)">{{ $t('table.details') }}</el-button>
          <el-button size="mini" type="text" @click="remove(scope.row)"><span class="gl_color_error">{{ $t('table.delete') }}</span></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row class="gl_pt_20" style="text-align: center;">
      <el-pagination
        :current-page="Api_GET_MessageGetReceivingMessagesQO.Page"
        :page-size="Api_GET_MessageGetReceivingMessagesQO.MaxResultCount"
        :total="totalPage"
        layout="total,sizes,prev,pager,next,jumper"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="sizeChange"
        @current-change="pageIndexChange"
      />
    </el-row>
    <write :is-write="isWrite" @showWrite="showWrite" />
    <message :is-detail="isDetail" :row-data="rowData" @showDetail="showDetail" />
  </div>
</template>

<script>
import { translateByCode } from '@/lib/getTransData';
import { Api_GET_MessageGetReceivingMessagesQO } from '@/lib/form/swaggerForm';
import {
  api_GET_MessageGetReceivingMessages,
  api_POST_MessageMarkMessageAsRead,
  api_DELETE_MessageDeleteReceiveingMessage,
  api_GET_MessageGetUnReadMessagesTotal
} from '@/extend/api/swaggerApi/chat.js';
import { mapState, mapActions } from 'vuex';
import write from './write';
import message from './message';
export default {
  name: 'Inbox',
  components: { write, message },
  data() {
    return {
      loading: false,
      deleteLoading: false,
      Api_GET_MessageGetReceivingMessagesQO: new Api_GET_MessageGetReceivingMessagesQO(),
      currentPage: 1, // 当前页
      totalPage: 0, // 总条目数
      isWrite: false, // 是否显示写通知
      isDetail: false, // 是否显示详情
      // isIconState: true, // 未读已读的状态
      statusList: [
        {
          code: 0,
          value: '未读'
        }
      ],
      inboxTable: [],
      rowData: { // 通知详情
        title: '标题',
        targetUsers: [],
        message: '内容',
        draftId: null
      },
      inboxSelection: [] // 选中的数据
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    })
  },
  created() {
    this.getDict().then(res => {
      this.statusList = res.chatReadType;
      for (let i = 0; i < this.statusList.length; i++) {
        this.statusList[i].code = Number(this.statusList[i].code);
      }
    });
    this.Api_GET_MessageGetReceivingMessagesQO.getMessageType = this.statusList[0].code; // 默认显示未读
    this.refreshList();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    getUnreadNum() {
      api_GET_MessageGetUnReadMessagesTotal().then(res => {
        this.$store.dispatch('permission/setRouterBadge', { Inbox: res });
      });
    },
    // 获得收到的消息
    refreshList(page) {
      this.loading = true;
      this.Api_GET_MessageGetReceivingMessagesQO.Page = page || 1;
      this.Api_GET_MessageGetReceivingMessagesQO.SkipCount = (this.Api_GET_MessageGetReceivingMessagesQO.Page - 1) * this.Api_GET_MessageGetReceivingMessagesQO.MaxResultCount;
      api_GET_MessageGetReceivingMessages(this.Api_GET_MessageGetReceivingMessagesQO).then(res => {
        this.inboxTable = res.items;
        this.totalPage = res.totalCount;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
      this.getUnreadNum();
    },
    // 查询
    query() {
      this.refreshList(this.Api_GET_MessageGetReceivingMessagesQO.Page);
    },
    // 选中的数据
    selection(val) {
      this.inboxSelection = val;
      // console.log(val);
    },
    // 全部标为已读
    changeState() {
      if (this.inboxTable.length > 0) {
        this.loading = true;
        const stateData = this.inboxTable.filter((value, index) => {
          return value.isRead === false;
        });
        const messageIDs = stateData.map(item => {
          return item.messageID;
        });
        const allMarkData = {
          messageIDs: messageIDs
        };
        api_POST_MessageMarkMessageAsRead(allMarkData).then(res => {
          this.loading = false;
          this.refreshList(this.Api_GET_MessageGetReceivingMessagesQO.Page);
        }).catch(() => {
          this.loading = false;
        });
      } else {
        this.$message({
          type: 'warning',
          message: translateByCode('alert.changeRead')
        });
      }
    },
    // 查看详情
    detail(row) {
      this.loading = true;
      const that = this;
      const markData = {
        messageIDs: [row.messageID]
      };
      that.rowData = { // 通知详情
        message: {
          title: row.title,
          messageDate: row.createTime,
          message: row.content
        }
      };
      that.isDetail = true;
      api_POST_MessageMarkMessageAsRead(markData).then(res => {
        that.loading = false;
      }).catch(() => {
        that.loading = false;
      });
    },
    showDetail(data) {
      this.isDetail = data;
    },
    // 编写新通知
    writeMessage() {
      this.isWrite = true;
    },
    showWrite(data) {
      this.isWrite = data;
    },
    // 单个删除
    remove(row) {
      this.$confirm(translateByCode('alert.wantDelete') + `[ ${row.title} ]` + translateByCode('alert.ma'), translateByCode('alert.delete'), {
        confirmButtonText: translateByCode('alert.confirm'),
        cancelButtonText: translateByCode('alert.cancel'),
        type: 'warning'
      }).then(() => {
        this.loading = true;
        const deleteMessage = [row.messageID];
        api_DELETE_MessageDeleteReceiveingMessage(deleteMessage).then(res => {
          this.loading = false;
          this.refreshList(this.Api_GET_MessageGetReceivingMessagesQO.Page);
          this.$message({
            type: 'success',
            message: translateByCode('alert.deleteSuccessfully')
          });
        }).catch(() => {
          this.loading = false;
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: translateByCode('alert.cancelDelete')
        });
      });
    },
    // 多个删除
    removeMore() {
      const messageIDList = this.inboxSelection.map(item => {
        return item.messageID;
      });
      if (this.inboxSelection && this.inboxSelection.length > 0) {
        this.$confirm(translateByCode('alert.removeMore'), translateByCode('alert.delete'), {
          confirmButtonText: translateByCode('alert.confirm'),
          cancelButtonText: translateByCode('alert.cancel'),
          type: 'warning'
        }).then(() => {
          this.deleteLoading = true;
          api_DELETE_MessageDeleteReceiveingMessage(messageIDList).then(res => {
            this.deleteLoading = false;
            this.refreshList(this.Api_GET_MessageGetReceivingMessagesQO.Page);
            this.$message({
              type: 'success',
              message: translateByCode('alert.deleteSuccessfully')
            });
          }).catch(() => {
            this.deleteLoading = false;
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: translateByCode('alert.cancelDelete')
          });
        });
      } else {
        this.$message({
          type: 'warning',
          message: translateByCode('alert.unableDelete')
        });
      }
    },
    // 分页
    sizeChange: function(MaxResultCount) {
      this.Api_GET_MessageGetReceivingMessagesQO.MaxResultCount = MaxResultCount; // 每页显示条目数
      this.refreshList();
    },
    pageIndexChange(currentPage) {
      this.refreshList(currentPage);
    }
  }
};
</script>

<style scoped>
.icon_color {
  color: red;
}
.el-table /deep/ .cell {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  line-height: 14px;
}
.el-table /deep/ .cell span img {
  max-width: 28px;
  max-width: 28px;
}
</style>
